package com.masu.knows.portal.controller;


import com.masu.knows.portal.exception.ServiceException;
import com.masu.knows.portal.model.Answer;
import com.masu.knows.portal.service.IAnswerService;
import com.masu.knows.portal.vo.AnswerVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 沈传尚
 * @since 2021-12-07
 */
@RestController
@RequestMapping("/v1/answers")
@Slf4j
public class AnswerController {
    @Autowired
    private IAnswerService answerService;

    // 讲师回复问题
    @PostMapping("")
    @PreAuthorize("hasRole('ROLE_TEACHER')")
    public Answer postAnswer(@Validated AnswerVo answerVo , BindingResult result ,
                             @AuthenticationPrincipal UserDetails details){
        log.debug("接受到表单信息:{}", answerVo);
        if (result.hasErrors()){
            String msg = Objects.requireNonNull(result.getFieldError()).getDefaultMessage();
            throw new ServiceException(msg);
        }
       return answerService.saveAnswer(answerVo, details.getUsername());
    }

    /**
     * 根据问题id获取回复(回答和评论)
     */
    @GetMapping(value = "/question/{id}")
    public List<Answer> getAnswer(@PathVariable("id") Integer id){
       return answerService.findAnswersAndComments(id);
    }


    /**
     * 回答采纳
     */
    @GetMapping(value = "/solved/{answerId}")
    public String solved(@PathVariable("answerId") Integer answerId,@AuthenticationPrincipal UserDetails user){
        boolean accept = answerService.accept(answerId, user.getUsername());
        if (accept){
            return "采纳完成";
        }else {
            return "该回答已被采纳";
        }

    }





}
